package com.cdtu.labpreview.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cdtu.labpreview.common.Result;
import com.cdtu.labpreview.common.UserHolder;
import com.cdtu.labpreview.dto.StudentDTO;
import com.cdtu.labpreview.dto.TeacherDTO;
import com.cdtu.labpreview.dto.UserDTO;
import com.cdtu.labpreview.entity.*;
import com.cdtu.labpreview.entity.Class;
import com.cdtu.labpreview.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 通用模块
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private TeacherClassMapper teacherClassMapper;
    @Value("${lp.path}")
    private String basePath;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result  upload(MultipartFile file){
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
//        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString()+suffix;

        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if(!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath+fileName));
        }catch (IOException e){
            e.printStackTrace();
        }
        return Result.ok(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream=new FileInputStream(new File(basePath+name));
            //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len=0;
            byte[] bytes=new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取老师对应班级列表，显示到下拉菜单
     * @return
     */
    @GetMapping("/class")
    public Result getClassListByTeacher(){
        int tno = UserHolder.getUser().getUserNo();//需要拦截器拦截保存用户信息
        //根据老师编号从TeacherClass关联表获取所有班级列表的id
        LambdaQueryWrapper<TeacherClass> lqw=new LambdaQueryWrapper<>();
        lqw.eq(TeacherClass::getTno,tno);
        List<TeacherClass> teacherClasses = teacherClassMapper.selectList(lqw);
        List<Long> cids = teacherClasses.stream().map(teacherClass -> teacherClass.getCid()).collect(Collectors.toList());
        //根据所有班级列表的主键cids获取班级名
        List<Class> classes = classMapper.selectBatchIds(cids);

        return Result.ok(classes);
    }

    /**
     * 获取科目列表，显示到下拉菜单
     * @return
     */
    @GetMapping("/subject")
    public Result getSubject(){

        List<Subject> subjects = subjectMapper.selectList(new LambdaQueryWrapper<>());
        return Result.ok(subjects);
    }

    /**
     * 获取所有班级列表，显示到下拉菜单
     * @return
     */
    @GetMapping("/getAllClass")
    public Result getClassList(){
        List<Class> classes = classMapper.selectList(new LambdaQueryWrapper<>());

        return Result.ok(classes);
    }


    /**
     * 获取用户信息进行首页显示
     * @return
     */
    @GetMapping("/user")
    public Result getUser(){
        UserDTO userDTO = UserHolder.getUser();
        int type = userDTO.getType();
        int userNo = userDTO.getUserNo();
        String name = userDTO.getName();
        if(type==1){
            StudentDTO studentDTO=new StudentDTO();
            Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>().eq(Student::getSno, userNo));
            long classId = student.getClassId();
            String className = classMapper.selectById(classId).getName();
            studentDTO.setSno(userNo);
            studentDTO.setName(name);
            studentDTO.setClassName(className);
            return Result.ok(studentDTO);
        }else if(type==2){
            TeacherDTO teacherDTO=new TeacherDTO();
            Teacher teacher = teacherMapper.selectOne(new LambdaQueryWrapper<Teacher>().eq(Teacher::getTno, userNo));
            long subjectId = teacher.getSubjectId();

            Subject subject = subjectMapper.selectById(subjectId);
            String subjectName = subject.getSubjectName();

            List<TeacherClass> teacherClasses = teacherClassMapper.
                    selectList(new LambdaQueryWrapper<TeacherClass>().eq(TeacherClass::getTno, userNo));
            List<Long> classIdList = teacherClasses.stream().map(teacherClass -> teacherClass.getCid()).collect(Collectors.toList());
            List<Class> classes = classMapper.selectBatchIds(classIdList);
//            List<String> classNameList = classes.stream().map(aClass -> aClass.getName()).collect(Collectors.toList());
            teacherDTO.setName(name);
            teacherDTO.setTno(userNo);
            teacherDTO.setSubjectName(subjectName);
            teacherDTO.setClasses(classes);
            return Result.ok(teacherDTO);
        }else {
            return Result.ok(name);
        }
    }

}
